package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.NewUserBean;
import com.atguigu.util.DateFormatUtil;
import com.atguigu.util.KafkaUtil;
import com.atguigu.util.MyClickHouseUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hfh
 * @version 1.0
 * @date 2022/9/3 19:26
 */
public class DwsUserNewUserWindow {
    public static void main(String[] args) throws Exception {
        //获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //设置状态后端
        /*env.enableCheckpointing(5*60*1000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.getCheckpointConfig().setCheckpointTimeout(3*60*1000L);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME","atguigu");*/

        //TODO 1 从kafka dwd_user_register 主题读取数据
        String topicName = "dwd_user_register";
        String groupId = "dws_user_new_user_window";

        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupId));

        //TODO 2 转换数据结构为JAVABean
        SingleOutputStreamOperator<NewUserBean> map = streamSource.map(new MapFunction<String, NewUserBean>() {
            @Override
            public NewUserBean map(String value) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                Long ts = jsonObject.getLong("ts");
                return NewUserBean.builder()
                        .newUserCt(1L)
                        .ts(ts)
                        .build();
            }
        });
//        map.print("map>>>>>");
        //TODO 3 设置水位线，开窗聚合
        SingleOutputStreamOperator<NewUserBean> timestampsAndWatermarks = map.assignTimestampsAndWatermarks(WatermarkStrategy.<NewUserBean>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                .withTimestampAssigner(new SerializableTimestampAssigner<NewUserBean>() {
                    @Override
                    public long extractTimestamp(NewUserBean element, long recordTimestamp) {
                        return element.getTs();
                    }
                }));

        SingleOutputStreamOperator<NewUserBean> reduce = timestampsAndWatermarks.windowAll(TumblingEventTimeWindows.of(Time.seconds(10L)))
                .reduce(new ReduceFunction<NewUserBean>() {
                    @Override
                    public NewUserBean reduce(NewUserBean value1, NewUserBean value2) throws Exception {
                        value1.setNewUserCt(value1.getNewUserCt() + value2.getNewUserCt());
                        return value1;
                    }
                }, new AllWindowFunction<NewUserBean, NewUserBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<NewUserBean> values, Collector<NewUserBean> out) throws Exception {
                        NewUserBean next = values.iterator().next();
                        next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        out.collect(next);
                    }
                });

        reduce.print("reduce>>>>>");
        //TODO 4 写入Hbase
        reduce.addSink(MyClickHouseUtil.<NewUserBean>getSink("insert into dws_user_new_user_window values(?,?,?,?)"));

        env.execute(groupId);
    }
}
